/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, {Component} from 'react';
import {
    Alert,
    DeviceEventEmitter,
    Image,
    ListView,
    ScrollView,
    StyleSheet,
    Text,
    TouchableHighlight,
    TouchableOpacity,
    View
} from 'react-native';

import Navigation from "../../../custom/Navigation";
import StyleUtils from "../../../res/styles/StyleUtils";
import ViewUtils from "../../../utils/ViewUtils";
import EditAddress from "./EditAddress";
import IparNetwork, {SERVER_TYPE} from "../../../httpUtils/IparNetwork";
import AddAddressPage from "./AddAddressPage";
import CommonUtils from "../../../common/CommonUtils";
import I18n from "../../../res/language/i18n";
import AlertDialog from "../../../custom/AlertDialog";

let ds;
export default class AddressPage extends Component<> {

    constructor(props) {
        super(props);
        ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.state = {
            dataSource: ds.cloneWithRows([]),
            noData: false,
            showDialog: false
        };
        this.iparNetwork = new IparNetwork()
    }

    componentWillUnmount() {
        this.iparNetwork = null;
    }

    componentDidMount() {
        CommonUtils.getAcyncInfo('userInfo')
            .then((result) => {
                this.userID = JSON.parse(result).main_user_id;
                this.getAddressInfo(this.userID);
            });

    }


    /*获取用户收货地址信息姐*/
    getAddressInfo(userID) {
        CommonUtils.showLoading();
        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'useraddress/list?', 'user_id=' + userID)
            .then((result) => {
                if (!result.code) {
                    this.setState({
                        dataSource: ds.cloneWithRows(result)
                    });
                }
                CommonUtils.dismissLoading();
                if (result.length <= 0) {
                    this.setState({noData: true})
                }

            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                this.setState({noData: true});
                console.log(error);
            })
    }

    /*删除用户地址信息*/
    deleteAddress(addressId) {


        this.iparNetwork.getRequest(SERVER_TYPE.logistics + 'useraddress/delete?', 'address_id=' + addressId)
            .then((result) => {

                CommonUtils.showLoading();

                if (addressId === this.props.selectAddressId) {
                    this.props.callback && this.props.callback(null)
                }

                this.getAddressInfo(this.userID)
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error);
            })
    }


    /*收货地址Tv*/
    getCountryTv(address) {
        let countryTv = [];
        for (i = 0; i < address.length; i++) {
            if (address[i] !== undefined) {
                countryTv.push(<Text
                    style={[StyleUtils.smallTvColor, StyleUtils.smallFont, styles.listTv]}>{address[i]}</Text>)
            }
        }
        return countryTv;
    }

    /*关闭alert*/
    closeDialog() {
        this.setState({showDialog: false});
    }

    render() {
        return (
            <View style={StyleUtils.flex}>
                <Navigation
                    onClickLeftBtn={() => {
                        this.props.navigator.pop()
                    }}
                    leftButtonIcon={require('../../../res/images/ic_back.png')}
                    titleImage={require('../../../res/images/ic_ipar_logo.png')}

                />
                <AlertDialog
                    visible={this.state.showDialog}
                    requestClose={() => this.closeDialog()}
                    contentTv={I18n.t('default.delete')}
                    leftBtnOnclick={() => {
                        this.deleteAddress(this.itemId);
                        this.closeDialog();
                    }}
                />
                <ScrollView>
                    <View style={[StyleUtils.flex]}>
                        {ViewUtils.getTitleView(I18n.t('default.address'), I18n.t('default.myAddressTitle'))}
                        {this.state.noData ? <Text
                            style={[StyleUtils.noData, StyleUtils.smallFont]}>{I18n.t('default.noData')}</Text> : false}
                        <ListView
                            renderRow={this.renderRow.bind(this)}
                            dataSource={this.state.dataSource}
                        />


                    </View>
                </ScrollView>

                {/**bottom*/}
                <View style={[{paddingRight: 16, paddingLeft: 16, paddingBottom: 30}]}>
                    {ViewUtils.getButton(I18n.t('default.newAddAddress'), () => this.props.navigator.push({
                        component: AddAddressPage,
                        name: 'AddAddressPage',
                        params: {
                            callback: (d) => {
                                if (d) {
                                    CommonUtils.showLoading();

                                    this.getAddressInfo(this.userID);
                                }
                            }
                        }
                    }))}
                </View>
            </View>)


    }


    selectShippingAddress(rowData) {
        if (this.props.callback) {
            this.props.callback(rowData);
            this.props.navigator.pop();
        }
    }


    /**
     * 设置默认地址
     */
    setDefaultAddress(editData) {
        CommonUtils.showLoading();


        let formData = new FormData();
        // formData.append('userId', this.userID);
        // formData.append("addressId", editData.addressId);
        // formData.append("defaultAddress", 1);
        // formData.append("streetName", editData.streetName);
        // formData.append("building", editData.building);
        // formData.append("postcode", editData.postCode);
        // formData.append("userName", editData.userName);
        // formData.append("mobile", editData.mobile);
        // formData.append("id", editData.id);


        formData.append('id', editData.id);
        formData.append('building', editData.building);
        formData.append('mobile', editData.mobile);
        formData.append('userId', this.userID);
        formData.append('userName', editData.userName);
        formData.append('addressId', editData.addressId);
        formData.append('streetName', editData.streetName);
        formData.append('defaultAddress', 1);
        formData.append('postCode', editData.postCode);
        formData.append('iso', editData.iso);
        formData.append('region1', editData.region1);
        formData.append('region2', editData.region2);
        formData.append('region3', editData.region3);
        formData.append('region4', editData.region4);
        formData.append('language', I18n.locale);
        formData.append('address', editData.address);

        /**
         id:920
         building:kjkjkj
         mobile:13070447353
         userId:659b51bc-e465-3d5a-ab04-d78ad56bd27a
         userName:om
         addressId:51123
         streetName:9779889
         defaultAddress:1
         postCode:831100
         iso:CN
         region1:شىنجاڭ
         region2:سانجى ئوبلاستى
         region3:سانجى شەھىرى
         region4:null
         language:UY
         address:شىنجاڭ,سانجى ئوبلاستى,سانجى شەھىرى,9779889,kjkjkj
         */

        this.iparNetwork.getPostFrom(SERVER_TYPE.logistics + 'useraddress/update', formData)
            .then((result) => {
                CommonUtils.dismissLoading();

                if (result.code === 200) {
                    if (this.props.callback) {
                        this.props.callback(editData);
                    }
                }
                console.log(result)
                this.props.navigator.pop();
            })
            .catch((error) => {
                CommonUtils.dismissLoading();

                console.log(error)
            })
    }

    /*list renderRow*/
    renderRow(rowData, sectionID, rowID) {

        return <View style={{
            backgroundColor: rowData.defaultAddress === false ? 'white' : '#f5f6f7',
            padding: 16,
            borderBottomWidth: 1,
            borderColor: '#ececec'
        }}>
            <TouchableHighlight
                activeOpacity={0.7}
                underlayColor={'#ededed'}
                onPress={() => this.selectShippingAddress(rowData)}>
                <View>
                    <Text
                        style={[{
                            marginTop: 16,
                            fontSize: 14,
                            color: 'black',
                            textAlign: 'left'

                        }, StyleUtils.smallFont]}>{I18n.t('default.shippingAddress')}</Text>

                    {this.getCountryTv([rowData.userName, rowData.mobile, rowData.address, rowData.postCode])}
                </View>
            </TouchableHighlight>
            {/*<Text style={{marginTop: 16, fontSize: 18, color: 'black'}}>Shipping address</Text>*/}


            {/*tabBox*/}
            <View style={[styles.tabBox, {backgroundColor: rowData.defaultAddress === false ? 'white' : '#f5f6f7'}]}>
                <Text numberOfLines={1} style={[styles.editTv, StyleUtils.smallFont]}
                      onPress={() => {
                          this.props.navigator.push({
                              component: EditAddress,
                              params: {
                                  editData: rowData,
                                  callback: (d) => {
                                      if (d) {
                                          CommonUtils.showLoading();

                                          this.getAddressInfo(this.userID);
                                      }
                                  }
                              }
                          })
                      }}>{I18n.t('default.edit')}</Text>
                <Text numberOfLines={1} style={[styles.editTv, StyleUtils.smallFont]}
                      onPress={() => {
                          this.itemId = rowData.id;
                          this.setState({showDialog: true})
                      }}>{I18n.t('default.delete')}</Text>


                <Text
                    onPress={() => rowData.defaultAddress === false ? this.setDefaultAddress(rowData) : null}
                    numberOfLines={1}
                    style={[styles.editTv, StyleUtils.smallFont]}>{rowData.defaultAddress === false ? I18n.t('default.setDefault') : I18n.t('default.defaultTv')}</Text>
            </View>
        </View>
    }

}

const styles = StyleSheet.create({
    lineStyle: {
        marginTop: 16,
        height: 1,
        width: '100%',
        backgroundColor: '#eeeeee'
    },
    tabBox: {
        height: 40,
        marginTop: 20,
        marginRight: '25%',
        flexDirection: 'row',
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    },
    listTv: {
        marginTop: 8,
        color: 'black',
        lineHeight: 16,
        textAlign: 'left',
        fontSize: 14,
        // padding

    },
    editTv: {
        fontSize: 12,
        color: 'black',
        flex: 1,
        textAlign: 'center'

    },
    btnBox: {
        padding: 16,
        paddingTop: 0,
        backgroundColor: 'rgba(255, 255, 255, 0.88)',
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        zIndex: 1
    },
});

